package com.shaoshaohuo.app.framework;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;

import com.shaoshaohuo.app.entity.Addressinfo;
import com.shaoshaohuo.app.entity.Baoxian;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.BaseUserInfo;
import com.shaoshaohuo.app.entity.UserEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity.UserInfo;
import com.shaoshaohuo.app.entity.brandscope.BrandScope;
import com.shaoshaohuo.app.framework.log.LogUtil;
import com.shaoshaohuo.app.listener.AuthCheckListener;
import com.shaoshaohuo.app.listener.UserInfoListener;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.LoginActivity;
import com.shaoshaohuo.app.ui.MyInfoActivity;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by yusonglin on 2015/7/29. Description: account manager
 */
public class AccountManager {

    /**
     * @Description isLogin
     */
    public static final boolean isLogin() {
        boolean result = false;
        if (!TextUtils.isEmpty(getAuthToken())) {
            result = true;
        }
        return result;
    }

    public static void saveAccount(UserEntity user) {
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_ID, user.getData().getUserid());
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_TOKEN, user.getData().getUsertoken());
    }

    public static void saveUserInfo(UserInfo userInfo) {
        LogUtil.i("AccountManager", "Verify Status: " + userInfo.getVerifystatus());
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_IS_AUTH, userInfo.getVerifystatus());
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.CAR_IS_AUTH, userInfo.getCarinfo().getVerifystatus());
        SharedPreferencesHelper.setString("Realname", userInfo.getBaseinfo().getRealname());
        SharedPreferencesHelper.setString("Mobile", userInfo.getBaseinfo().getMobile());
        SharedPreferencesHelper.setString("Nickanme", userInfo.getBaseinfo().getNickname());
        SharedPreferencesHelper.setString("Avatar", userInfo.getBaseinfo().getAvatar());
        SharedPreferencesHelper.setString("isHavePasswd", userInfo.getIsHavePasswd());
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_CARD_NUM, userInfo.getBaseinfo().getIdnum());
        saveAddress(userInfo.getAddressinfo());
        saveBrandScope(userInfo.getBrandScope());
    }

    private static void saveBrandScope(BrandScope brandScope) {
        if (brandScope != null) {
            SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BRAND_SCOPR_AUDIT_STATUS, brandScope.getAuditStatus() + "");
            SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BRAND_SCOPR_NAME, brandScope.getName());
            SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BRAND_SCOPR_SHOP_NAME, brandScope.getShopName());
            SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BRAND_SCOPR_AREA_ID, brandScope.getCity());
            SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BRAND_SCOPR_ADDRESS_DETAIL, brandScope.getDetailAddress());
            SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BRAND_SCOPR_RECEIVE_GOODS_TIME, brandScope.getReceiveGoodsTime());
        }
    }

    public static void saveAddress(List<Addressinfo> list) {
        if (list != null && list.size() > 0) {
            Addressinfo addressinfo = list.get(0);
            SharedPreferencesHelper.setString("address", addressinfo.getId());
        }
    }

    public static String getAddress() {
        String addressId = SharedPreferencesHelper.getString("address", "0");
        if (!"0".equals(addressId)) {
            String areaFullname = AreaUtil.getAreaFullname(addressId);
            return areaFullname;
        }
        return null;
    }


    public static boolean isUserAuth() {
        return "3".equals(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.USER_IS_AUTH, ""));
    }

    public static boolean isCarAuth() {
        return "3".equals(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.CAR_IS_AUTH, ""));
    }

    public static void saveBaoxian(Baoxian baoxian) {
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BAOXIAN_PRICE, baoxian.getBxprice());
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.BAOXIAN_MONEY, baoxian.getBxmoney());
    }

    public static Baoxian getBaoxian() {
        String bxprice = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BAOXIAN_PRICE, "");
        String bxmoney = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BAOXIAN_MONEY, "");
        Baoxian bx = new Baoxian();
        bx.setBxprice(bxprice);
        bx.setBxmoney(bxmoney);
        return bx;
    }


    public static void saveRealName(String realname) {
        SharedPreferencesHelper.setString("Realname", realname);
    }

    public static BaseUserInfo getUserInfo() {
        String realname = SharedPreferencesHelper.getString("Realname", "");
        String mobile = SharedPreferencesHelper.getString("Mobile", "");
        String nickanme = SharedPreferencesHelper.getString("Nickanme", "");
        String avatar = SharedPreferencesHelper.getString("Avatar", "");
        BaseUserInfo info = new BaseUserInfo();
        info.setAvatar(avatar);
        info.setMobile(mobile);
        info.setRealname(realname);
        info.setNickname(nickanme);
        return info;
    }

    /**
     * 获取当前用户的ID
     *
     * @return
     */
    public static String getUserId() {
        return SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.USER_ID, "");
    }

    public static String getUserAuthStatus() {
        return SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.USER_IS_AUTH, "");
    }

    public static String getCarAuthStatus() {
        return SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.CAR_IS_AUTH, "");
    }

    /**
     * 获取用户的品牌直营资料信息
     * @return
     */
    public static BrandScope getBrandScope() {
        BrandScope brandScope = null;
        String auditStatus = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BRAND_SCOPR_AUDIT_STATUS, "");
        if (!StringUtil.isEmpty(auditStatus)) {
            brandScope = new BrandScope();
            brandScope.setAuditStatus(Integer.parseInt(auditStatus));
            brandScope.setCity(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BRAND_SCOPR_AREA_ID, ""));
            brandScope.setDetailAddress(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BRAND_SCOPR_ADDRESS_DETAIL, ""));
            brandScope.setName(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BRAND_SCOPR_NAME, ""));
            brandScope.setReceiveGoodsTime(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BRAND_SCOPR_RECEIVE_GOODS_TIME, ""));
            brandScope.setShopName(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.BRAND_SCOPR_SHOP_NAME, ""));
        }

        return brandScope;
    }

    /**
     * @return user auth token
     */
    public static String getAuthToken() {
        return SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.USER_TOKEN, "");
    }

    /**
     * @des logout
     */
    public static void logout(Context context) {
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_ID, "");
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_TOKEN, "");
        SharedPreferencesHelper.setLong(context, SharedPreferencesHelper.Field.SIGN_TIME, 0);
        SharedPreferencesHelper.setInt(context, SharedPreferencesHelper.Field.DEFAULT_DISPLAY.name(), 0);
        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_CARD_NUM, "");
        //注销此机型上的 别名
        JPushInterface.setAliasAndTags(context, "", null, new TagAliasCallback() {
            @Override
            public void gotResult(int arg0, String arg1, Set<String> arg2) {
            }
        });

        // DaoUtils.deleteUserInfo();

    }

    public static void authExpiredAndLogin(Context context) {
        logout(context);
        ToastUtil.toast("重新登录");
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    public static boolean checkLogin(final Context context) {
        if (AccountManager.isLogin()) {
            return true;
        } else {
            context.startActivity(new Intent(context, LoginActivity.class));
        }
        return false;
    }

    public static boolean checkUserAuth(final Context context) {
        if (AccountManager.isLogin()) {
            String authStatus = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.USER_IS_AUTH, "");
            if ("3".equals(authStatus)) {
                return true;
            } else if ("4".equals(authStatus)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("您的身份尚在审核中");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.create().show();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("请先完善认证信息?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toAuthInfo(context, false);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.create().show();

            }

        } else {
            context.startActivity(new Intent(context, LoginActivity.class));
        }
        return false;
    }

    public static void updateUserInfo(final Context context) {
        RequestService.getInstance().getUserInfo(context, UserInfoEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    AccountManager.saveUserInfo(entity.getData());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {

            }
        });
    }

    public static void updateUserInfo(final Context context, final UserInfoListener listener) {
        RequestService.getInstance().getUserInfo(context, UserInfoEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    AccountManager.saveUserInfo(entity.getData());
                    if (listener != null) {
                        listener.onUpdateUserInfo(entity);
                    }
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {

            }
        });
    }

    public static void updateUserInfo(final Context context, final AuthCheckListener listener) {
        RequestService.getInstance().getUserInfo(context, UserInfoEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    AccountManager.saveUserInfo(entity.getData());
                    if (listener != null) {
                        listener.authCheckSucceed(entity.getData().getCarinfo().getVerifystatus());
                    }
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {

            }
        });
    }

    public static void checkCarAuth(final Context context, final AuthCheckListener listener) {
        if (AccountManager.isLogin()) {

            String authStatusLocal = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.CAR_IS_AUTH, "");
            if (AuthCheckListener.AUTH_OK.equals(authStatusLocal)) {
                if (listener != null) {
                    listener.authCheckSucceed(AuthCheckListener.AUTH_OK);
                }
            } else {
                updateUserInfo(context, new AuthCheckListener() {
                    @Override
                    public void authCheckSucceed(String authStatus) {
                        if (AuthCheckListener.AUTH_OK.equals(authStatus)) {
                            listener.authCheckSucceed(AuthCheckListener.AUTH_OK);

                            //
                        } else if (AuthCheckListener.AUTH_IN_PROGRESS.equals(authStatus)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setMessage("您的车辆信息尚在审核中");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.create().show();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setMessage("请先完善车辆信息?");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    toAuthInfo(context, true);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                            builder.create().show();
                        }
                    }

                    @Override
                    public void authCheckFailured(String errCode, String errDesc) {

                    }
                });


            }
        } else {
            context.startActivity(new Intent(context, LoginActivity.class));
        }
    }

    @Deprecated
    public static boolean checkCarAuth(final Context context) {
        if (AccountManager.isLogin()) {

            String authStatus = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.CAR_IS_AUTH, "");
            if ("3".equals(authStatus)) {
                return true;
            } else {
                updateUserInfo(context);

                if ("4".equals(authStatus)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setMessage("您的车辆信息尚在审核中");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.create().show();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setMessage("请先完善车辆信息?");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            toAuthInfo(context, true);
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.create().show();
                }
            }
        } else {
            context.startActivity(new Intent(context, LoginActivity.class));
        }
        return false;
    }

    private static void toAuthInfo(final Context context, boolean authCar) {
            context.startActivity(new Intent(context, MyInfoActivity.class));
    }

}
